package com.heima.schedule.service.Impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.TaskDto;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Set;

@Slf4j
@Service
@Transactional
public class TaskServiceImpl implements TaskService {
    @Autowired
    private TaskinfoMapper taskinfoMapper;
    @Autowired
    private TaskinfoLogsMapper taskinfoLogsMapper;
    @Autowired
    private CacheService cacheService;

    /**
     * 添加任务
     * @param dto
     */
    @Override
    public long addTask(TaskDto dto) {
        //
        long taskId = IdWorker.getId();
        dto.setTaskId((taskId));

        //1.添加任务到数据库中
        boolean res = addTaskToDB(dto);
        if(res){
            //2.添加符合条件的任务到redis
            addTaskToRedis(dto);
        }

        return taskId;
    }


    /**
     * 按照类型和优先级来 消费任务
     * @param type
     * @param priority
     */
    @Override
    public TaskDto poll(int type, int priority) {
        //1.将任务从redis的list中取出
        String key = ScheduleConstants.TOPIC + type + "_" + priority;
        String taskJson = cacheService.lRightPop(key);
        TaskDto taskDto = JSON.parseObject(taskJson, TaskDto.class);

        if(taskDto == null) return null;

        //2.删除taskInfo中的相关数据
        taskinfoMapper.deleteById(taskDto);

        //3.更新taskInfoLogs中的数据
        TaskinfoLogs logs = taskinfoLogsMapper.selectById(taskDto);
        logs.setStatus(ScheduleConstants.EXECUTED);
        taskinfoLogsMapper.updateById(logs);

        return taskDto;
    }

    /**
     * redis定时刷新：ZSet --> List
     * */
    @Scheduled(cron = "0 */1 * * * ?")
    public void refreshRedis(){
        log.info("将ZSet中符合条件的数据刷新到List中...");
        Set<String> zSetKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");//“分页查询”ZSet中的数据（以future开头）
        for (String futureKey : zSetKeys) {
            Set<String> tasks = cacheService.zRangeByScore(futureKey,0,System.currentTimeMillis());//任务执行时间 <= 当前系统时间 的数据（即要刷新转移的数据）

            String key = futureKey.split(ScheduleConstants.FUTURE)[1];//["","1001_1]
            String topicKey = ScheduleConstants.TOPIC + key;//list和ZSet表数据的键不同之处是 topic/future 开头

            if(tasks != null && tasks.size() > 0)
                //根据topicKey将tasks添加到List中
                //根据futureKey找到对应的ZSet中的tasks并将其删除
                cacheService.refreshWithPipeline(futureKey,topicKey,tasks);
        }
    }

    /**
     * DB中的任务定时刷洗到redis
     * */
    @Scheduled(cron = "0 */5 * * * ?")
    public void refreshDBToRedis(){
        //1.清空redis中的任务
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        Set<String> futureKeys = cacheService.scan(ScheduleConstants.FUTURE + "*");

        cacheService.delete(topicKeys);
        cacheService.delete(futureKeys);

        //2.查询数据库中未来5分钟内的任务
        Date futureTime = new Date(System.currentTimeMillis() + (1000 * 60 * 5));
        List<Taskinfo> taskinfos = taskinfoMapper.selectList(Wrappers.<Taskinfo>lambdaQuery().le(Taskinfo::getExecuteTime, futureTime));

        //将目标任务同步到redis
        for (Taskinfo taskinfo : taskinfos) {
            TaskDto dto = new TaskDto();
            BeanUtils.copyProperties(taskinfo,dto);
            dto.setExecuteTime(taskinfo.getExecuteTime().getTime());

            addTaskToRedis(dto);
        }
    }


    //添加符合条件的任务到redis
    private void addTaskToRedis(TaskDto dto) {
        String key = dto.getTaskType() + "_" + dto.getPriority();

        //1.任务执行时间 <= 当前系统时间：将任务添加到List中
        if(dto.getExecuteTime() <= System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key, JSON.toJSONString(dto));

            //2.任务执行时间 <= 当前系统时间 + 5分钟：将任务添加到ZSet中
        }else if(dto.getExecuteTime() <= System.currentTimeMillis() + (1000*60*5)){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(dto),dto.getExecuteTime());
        }
    }


    //添加任务到数据库
    private boolean addTaskToDB(TaskDto dto) {
        boolean flag = false;

        try {
            //1.先存入taskInfo
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(dto,taskinfo);
            taskinfo.setExecuteTime(new Date(dto.getExecuteTime()));//dto中的时间类型是long ->Date
            taskinfoMapper.insert(taskinfo);

            //2.再存入taskInfo_logs
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(dto,taskinfoLogs);
            taskinfoLogs.setExecuteTime(new Date(dto.getExecuteTime()));
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.SCHEDULED);
            taskinfoLogsMapper.insert(taskinfoLogs);

            flag = true;
        } catch (BeansException e) {
            e.printStackTrace();
        }

        return flag;
    }


}
